<template>
  <div>
    <a-select
      v-model="val"
      v-bind="$attrs"
      show-search
      placeholder="请选择"
      style="width: 100%"
      :filter-option="false"
      :not-found-content="fetching ? undefined : '未查询到内容'"
      @search="remoteSearch"
      @change="handleChange"
    >
      <a-spin v-if="fetching" slot="notFoundContent" size="small" />
      <a-select-option
        v-for="item in option"
        :key="item[opetionValue]"
        :value="item[opetionValue]"
      >
        {{ item[opetionLabel] }}
      </a-select-option>
    </a-select>
  </div>
</template>
<script>
import debounce from 'lodash/debounce'

export default {
  props: {
    value: {
      type: [String, Number, Array],
      default: ''
    },
    url: {
      type: String,
      default: ''
    },
    defaultValue: {
      type: [String, Number, Array],
      default: ''
    },
    paginate: {
      type: Boolean,
      default: false
    },
    opetionLabel: {
      type: String,
      default: 'name'
    },
    keywordKey: {
      type: String,
      default: 'name'
    },
    opetionValue: {
      type: String,
      default: 'id'
    }
  },
  data() {
    this.remoteSearch = debounce(this.search, 800)
    return {
      val: this.value === null ? undefined : this.value,
      fetching: false,
      option: []
    }
  },
  watch: {
    value(val) {
      this.val = val === null ? undefined : val
    },
    defaultValue: {
      handler(val) {
        if (val) {
          const queryIds =
            Object.prototype.toString.call(val) === '[object Array]'
              ? val
              : [val]

          this.search('', queryIds)
        }
      },
      immediate: true
    }
  },

  mounted() {
    if (this.val && this.paginate) {
      const queryIds =
        Object.prototype.toString.call(this.val) === '[object Array]'
          ? this.val
          : [this.val]

      this.search('', queryIds)
    } else {
      this.initSearch()
    }
  },
  methods: {
    initSearch() {
      this.search('')
    },
    search(value = '', ids) {
      if (!this.url) {
        return false
      }

      const paginateParams = this.paginate ? { pageNum: 1, pageSize: 100 } : {}

      this.fetching = true

      this.$api.plan
        .fetchList(this.url, {
          ids,
          [this.keywordKey]: value,
          ...paginateParams
        })
        .then(res => {
          this.fetching = false
          this.option = []
          this.option = [...Array.from(new Set(res.list || res))]
        })
    },
    handleChange(value) {
      this.val = value
      this.$emit('input', value)
      this.fetching = false
    }
  }
}
</script>
